// login.js

// 获取登录表单和错误信息元素
const loginForm = document.getElementById('login-form');
const errorMessage = document.getElementById('error-message');

// 监听表单提交事件
loginForm.addEventListener('submit', function(event) {
  event.preventDefault(); // 防止表单提交

  // 获取输入的账号和密码
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  const rememberMe = document.getElementById('remember-me').checked;

  // 使用jQuery的ajax方法发送POST请求到后端
  $.ajax({
    url: 'http://localhost:8083/api/login',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ username, password }),
    success: function(data) {
      if (data.code === 0) {
        // 登录成功处理
        alert('登录成功！');
        if (rememberMe) {
          localStorage.setItem('rememberMe', 'true');
          localStorage.setItem('username', username);
        } else {
          localStorage.removeItem('rememberMe');
          localStorage.removeItem('username');
        }

        // 根据用户角色跳转到不同页面
        switch (data.data.roleType) {
          case 0:
            window.location.href = './root/root-management.html';
            break;
          case 1:
            window.location.href = './manager/index.html';
            break;
          case 2:
            window.location.href = './teacher/home.html';
            break;
          case 3:
            window.location.href = './student/student-home.html';
            break;
        }
      } else {
        // 登录失败处理
        errorMessage.textContent = data.msg || '账号或密码错误，请重试。';
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.error('Error:', textStatus, errorThrown);
      errorMessage.textContent = '网络错误，请稍后再试';
    }
  });
});

// 检查是否有记住密码的设置
window.onload = function() {
  const rememberMe = localStorage.getItem('rememberMe');
  if (rememberMe) {
    const username = localStorage.getItem('username');
    document.getElementById('username').value = username;
    document.getElementById('remember-me').checked = true;
  }
};
